package com.theanh.RssActivity.updater;

import android.database.SQLException;
import android.graphics.Bitmap;
import android.util.Log;

import com.theanh.RssActivity.Store;
import com.theanh.RssActivity.db.DbAdapter;
import com.theanh.RssActivity.entity.Channel;
import com.theanh.RssActivity.entity.Item;
import com.theanh.RssActivity.ui.model.ChannelModel;
import com.theanh.RssActivity.util.Constants;
import com.theanh.RssActivity.util.DbUtils;
import com.theanh.RssActivity.util.DialogUtils;
import com.theanh.RssActivity.util.FileUtils;
import com.theanh.RssActivity.util.RssUtils;
import com.theanh.RssActivity.util.Utils;

public class ChannelUpdater extends Thread {

	private static final String TAG = "ChannelUpdater";
	private Channel channel;
	private boolean running = false;
	private ChannelModel model;

	public ChannelModel getModel() {
		return model;
	}

	public void setModel(ChannelModel model) {
		this.model = model;
	}

	public ChannelUpdater(Channel channel) {
		super();
		this.channel = channel;
		this.setDaemon(true);
	}

	public boolean isRunning() {
		return running;
	}

	public void setRunning(boolean running) {
		this.running = running;
	}

	@Override
	public void run() {
		if (channel == null)
			return;

		try {
			// Update model
			if (model != null) {
				model.beginUpdate();
			}

			try {
				RssUtils.fillChannel(channel);
			} catch (Exception e) {
				Log.e(TAG, e.toString());
				model.errorUpdate(e.getMessage());
			}

			if (channel == null || channel.getItems() == null
					|| channel.getItems().size() == 0)
				return;

			DbAdapter dbAdapter = null;

			long count = 0;
			try {
				dbAdapter = DbUtils.createAndOpenDbAdapter();
				// Update logo's url
				dbAdapter.updateChannel(channel);
				
				// Insert items for channel
				for (Item item : channel.getItems()) {
					if (item == null)
						continue;
					
//					Log.i(TAG, item.toString());
					if (item.validate()) {
						if (!dbAdapter.checkItemExist(item)) {
							count += dbAdapter.insertItem(item);
						}
					}
				}
				
				// Save logo's channel to local
				saveLogo();
			} catch (SQLException ex) {
				// TODO: Show message dialog
				Log.e(TAG, ex.toString());
			} finally {
				if (dbAdapter != null) {
					try {
						DbUtils.closeDbAdapter(dbAdapter);
					} catch (SQLException ex) {
						Log.e(TAG, ex.toString());
					}
				}
			}
		} finally {
			// Update model
			if (model != null) {
				model.endUpdate();
			}
		}
	}
	
	private void saveLogo(){
		
		if (channel == null || channel.getLogoUrl() == null || channel.getLogoUrl().length() == 0)
			return;
		
		Bitmap logo = Utils.loadImage(channel.getLogoUrl());
		if (logo != null) {
			// Save logo's channel to local
			FileUtils.writeImage(logo, Constants.CHANNEL_LOGO_PREFIX + channel.getID());
		}
	}

}
